<template>
  <div>
    <el-upload
    class="avatar-uploader"
    name="picture"
    :action="`${BASE}/base/upload`"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="`${BASE}${imageUrl}`" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
  <el-button type="primary" @click="handleUser">修改</el-button>
  </div>
</template>

<script>
import {BASE} from '../../config/index'
import {userUpdate} from '../../api/user'
export default {
  data() {
    return {
      imageUrl: "",
      BASE
    };
  },
  computed: {
    userInfo() { //提取用户信息，可能有avatar
      return this.$store.state.user.userInfo 
    }
  },
  created () {
    let {avatar} = this.userInfo
    if(avatar){
      this.imageUrl = avatar  //展示旧头像
    }
  },
  methods: {
    handleUser(){ //向数据库更新用户信息
      userUpdate(this.userInfo._id,{ //更新线上
        avatar:this.imageUrl
      }).then(res=>{
        console.log(res);
        let info = this.userInfo //旧的用户信息
        info.avatar = this.imageUrl
        localStorage.setItem('userInfo',JSON.stringify(info)) //更新本地存储
        this.$store.commit('user/initUserInfo',{info})  //更新状态机
      })
    },
    handleAvatarSuccess(res, file) {  //图片上传成功后的回调
      console.log(res);
      let {url} = res.data
      this.imageUrl = url
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) { //上传图片之前的验证函数，约束文件类型，保证服务器安全性
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
